<?php
/**
 * Created by PhpStorm.
 * User: yhg97p
 * Date: 2016/7/8
 * Time: 11:51
 */
session_start();
include __DIR__ . '/vendor/autoload.php';

use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;

$options = [
    'debug' => true,
    'app_id' => 'wx1cd5b8a5438c2130',
    'secret' => 'd65240fc907d1aad8d3386ea60d2726e ',
    'token' => 'w0Q52Arls2S9T2qlsRA215q09q2L9R2z',
    'aes_key' => 'Veg9MEUnmztEYnsJgniStH3ifk8O0RmlBQKzvUuwHXE',

    'log' => [
        'level' => 'debug',
        'file' => __DIR__ . '/log/' . date('Y-m-d') . '.log',
    ],
    'guzzle' => [
        'timeout' => 3.0, // 超时时间（秒）
        'verify' => __DIR__ . '/cert/rootca.pem',
    ],

    'oauth' => [
        'scopes'   => ['snsapi_base'],  //snsapi_base | snsapi_userinfo
        'callback' => 'http://'.$_SERVER['SERVER_NAME'].'/wx/oauth_callback.php',    //回调地址
    ],

    'payment' => [
        'merchant_id'        => '1340811701',
        'key'                => '3599d7bf0013d6a272b4d6d84c167296',
        'cert_path'          => __DIR__ . '/cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
        'key_path'           => __DIR__ . '/cert/apiclient_key.pem',      // XXX: 绝对路径！！！！
        'notify_url'         => 'http://'.$_SERVER['SERVER_NAME'].'/wx/payback.php',       // 你也可以在下单时单独设置来想覆盖它
    ],
];

$app = new Application($options);
$payment = $app->payment;
$response = $payment->handleNotify(function($notify, $successful){
    file_put_contents('payback.txt', 'responed JSON: at '.date('Y-m-d H:i:s').'; Data: '.json_encode($notify));
    // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
    //$notify->transaction_id 微信支付订单号
    //$notify->out_trade_no  商户自己订单号
    $order_no = $notify->out_trade_no;

    //检查支付时间或者支付状态,通知微信已经操作完成
    file_put_contents('payback.txt', 'responed JSON: at '.date('Y-m-d H:i:s').'; Data: '.$successful);
    if ($successful) {  //支付成功
        file_get_contents("http://".$_SERVER['SERVER_NAME']."/index.php?s=/Home/Share/paycallback/order_no/".$order_no.".html");
    } else { // 用户支付失败
        //修改状态为支付失败
    }
    return true; // 返回处理完成
});
return $response->send();